from flask import Blueprint, current_app
from flask import request
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity
import re
from app.models import db, Product
import app.utils as utils
import app.utils.market as market

product_main_bp = Blueprint('product_main_bp', __name__)


from app.models import User

# 统一为每个请求打印日志，通过“蓝图.before_request”和“蓝图.after_request”
@product_main_bp.before_request
def log_request_info():
    current_app.logger.info(f"收到请求: {request.method} {request.url}")
@product_main_bp.after_request
def log_response_info(response):
    current_app.logger.info(f"响应状态码: {response.status_code}")
    return response


@product_main_bp.get("/list")
@jwt_required()
def get_user_products():
    current_user_id = get_jwt_identity()
    user = User.query.get(current_user_id)
    if not user:
        return utils.error(message="用户不存在")

    products = user.products
    for p in products:
        if p.type == "股票":
            stock_info = market.get_latest_stock_info(p.code)
            if stock_info is None:
                return utils.error(message="股票最新信息查询失败")
            p.latest_price = stock_info["最新价"]
        elif p.type == "基金":
            fund_info = market.get_latest_fund_info(p.code)

            if fund_info is None:
                return utils.error(message="基金最新信息查询失败")
            p.latest_price = fund_info["最新净值"]

    return utils.success(data=[{
        "code": p.code,
        "name": p.name,
        "type": p.type,
        "cost_price" : p.cost_price,
        "latest_price": p.latest_price,
        "quantity" : p.quantity
    } for p in products])

@product_main_bp.post('/add')
@jwt_required()
def add_user_products():
    """
    批量添加用户的投资产品持仓信息
    """
    user_id = get_jwt_identity()

    data = request.get_json()
    if not isinstance(data, list) or not data:
        return utils.error("请求数据必须是非空的数组", code=1001)

    added_products = []  # 保存成功添加的产品
    failed_products = []  # 保存失败的产品及原因

    try:
        for item in data:
            try:
                code = item['code']
                name = item['name']
                type_ = item.get('type')
                industry = item.get('industry')
                quantity = item['quantity']
                cost_price = item['cost_price']

                if type_ == "股票":
                    stock_info = market.get_latest_stock_info(code)
                    latest_price = stock_info.get('最新价')
                    if latest_price is None:
                        failed_products.append({"code": code, "error": "无法获取股票最新价格"})
                        continue
                elif type_ == "基金":

                    fund_info = market.get_latest_fund_info(code)
                    print(fund_info)
                    latest_price = fund_info.get('最新净值')
                    if latest_price is None:
                        failed_products.append({"code": code, "error": "无法获取基金最新价格"})
                        continue
                else:
                    # 返回前端，不支持的类型
                    return utils.error("不支持的添加类型！")
                product = Product(
                    user_id=user_id,
                    code=code,
                    name=name,
                    type=type_,
                    industry=industry,
                    quantity=quantity,
                    cost_price=cost_price,
                    latest_price=latest_price
                )


                db.session.add(product)
                added_products.append({"code": code, "name": name})

            except KeyError as e:
                failed_products.append({"code": item.get('code', '未知'), "error": f"缺少字段：{str(e)}"})
            except Exception as e:
                failed_products.append({"code": item.get('code', '未知'), "error": f"添加失败：{str(e)}"})

        db.session.commit()
        return utils.success(
            message="批量添加完成",
            data={
                "added": added_products,
                "failed": failed_products
            }
        )
    except Exception as e:
        db.session.rollback()

        return utils.error(f"批量添加失败：{str(e)}", code=1003)
